// 注册模块别名
require('module-alias/register');
const { env } = require('process');
const nodemon = require('nodemon');
const path = require('path');
const { fsExistsSync } = require('./app/util');
const { syncTemplates } = require('./config/compiler/template_config');
const { readFilesRecursively } = require('./script/req_src');
const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout,
});

if (env.NODE_ENV === 'create') {
  const { create } = require('./config/create');
  create();
}

if (env.NODE_ENV === 'build') {
  const { build } = require('./config/build');
  build();
}

if (env.NODE_ENV === 'adminapi') {
  nodemon({
    script: 'admin/app/main.js',
    ignore: ['node_modules/', 'oemsaas/', 'src/', 'config/', '.git/', 'admin/react-liquid', 'app/'],
  }).on('start', function () {
    console.warn('重启');
  });
}

function askTemplateName(callback) {
  readline.question('请输入模板名: ', (templateName) => {
    const dir = path.join('./src/theme/', templateName); // 构建完整路径
    if (!fsExistsSync(dir)) {
      console.log('模板不存在');
      askTemplateName(callback);
      return;
    }
    callback(templateName);
  });
}

if (env.NODE_ENV === 'syncTemplate') {
  try {
    askTemplateName((templateName) => {
      syncTemplates(templateName, () => {
        readFilesRecursively(templateName, () => {
          readline.close();
        });
      });
    });
  } catch (e) {
    console.log(e);
    // 关闭 readline 接口
    readline.close();
  }
}
